/*
 * SDL.cpp
 *
 *  Created on: Feb 11, 2011
 *      Author: alki
 */

#include "SDL.h"

SDL::SDL(int width,int height,int bits,bool fullscreen) {
	this->m_width = width;
	this->m_height = height;
	this->m_bits = bits;
	this->m_fullscreen = fullscreen;
	this->m_surface = NULL;
	this->m_gl = NULL;
	this->m_done = false;
	this->m_active = true;

    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {
    	throw new Exception(NULL,__FILE__,__LINE__,"Video initialization failed",SDL_GetError());
	}

    const SDL_VideoInfo *videoInfo;

    videoInfo = SDL_GetVideoInfo( );

    if ( !videoInfo ) {
    	throw new Exception(NULL,__FILE__,__LINE__,"Video query failed",SDL_GetError());
	}


    this->m_videoflags  = SDL_OPENGL;          /* Enable OpenGL in SDL */
    this->m_videoflags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */
    this->m_videoflags |= SDL_HWPALETTE;       /* Store the palette in hardware */
//    this->m_videoflags |= SDL_RESIZABLE;       /* Enable window resizing */

    if(this->m_fullscreen)
    	this->m_videoflags |= SDL_FULLSCREEN;

    if ( videoInfo->hw_available )
    	this->m_videoflags |= SDL_HWSURFACE;
    else
    	this->m_videoflags |= SDL_SWSURFACE;

    if ( videoInfo->blit_hw )
    	this->m_videoflags |= SDL_HWACCEL;

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

    this->m_surface = SDL_SetVideoMode(this->m_width,this->m_height,this->m_bits,this->m_videoflags );

    if ( !this->m_surface ) {
    	throw new Exception(NULL,__FILE__,__LINE__,"Video mode set failed",SDL_GetError());
 	}

    this->m_gl = new GL();
    this->m_gl->SetResolution(this->m_width,this->m_height);
}

SDL::~SDL() {
	if(this->m_gl!=NULL)
		delete this->m_gl;

	SDL_Quit();
	exit(0);
}

void SDL::PollEvent() {
    SDL_Event event;

    while ( SDL_PollEvent( &event ) ) {
	    switch( event.type ) {
		case SDL_ACTIVEEVENT:
		    if ( event.active.gain == 0 )
		    	this->m_active = false;
		    else
		    	this->m_active = true;
		    break;
		case SDL_VIDEORESIZE:
		    this->m_surface = SDL_SetVideoMode(event.resize.w,event.resize.h,this->m_bits,this->m_videoflags);
		    if ( !this->m_surface ) {
		    	throw new Exception(NULL,__FILE__,__LINE__,"Could not get a surface after resize",SDL_GetError());
			}
		    this->m_gl->SetResolution(event.resize.w,event.resize.h);
		    break;
		case SDL_KEYDOWN:
		    this->HandleKeyPress( &event.key.keysym );
		    break;
		case SDL_QUIT:
		    this->m_done = true;
		    break;
		default:
		    break;
		}
	}
}

void SDL::HandleKeyPress( SDL_keysym *keysym )
{
    switch ( keysym->sym )
	{
	case SDLK_ESCAPE:
	    this->m_done = true;
	    break;
	case SDLK_F1:
	    SDL_WM_ToggleFullScreen( this->m_surface );
	    break;
	default:
	    break;
	}

    return;
}
